<template>
  <n-space vertical>
   <n-form
     ref="formRef"
     :model="model"
     label-placement="left"
     :label-width="100"
     class="setting-cont"
   >
   
     <n-form-item label="角色名称" >
       <n-input v-model:value="model.roleName" placeholder="请录入角色名称" />
     </n-form-item>
     <n-form-item label="角色代号" >
       <n-input v-model:value="model.role" placeholder="请录入角色代号" />
     </n-form-item>
     <n-form-item label="角色权限" >
       <n-tree
        block-line
        :data="routes[0].children"
        key-field="path"
        checkable
        cascade
        @update:checked-keys="handleCheck"
        :default-checked-keys="model.permission"
       />
     </n-form-item>
     <n-form-item label=" " >
       <n-button :type="!rowData?'primary':'info'" size="medium" block @click="handleRole">
         {{ rowData ? '修改角色':'确认新增' }}
       </n-button>
     </n-form-item>
     
   </n-form>
 </n-space>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import { routes } from '../../../router';
import { rolePostApi,roleUpdateApi } from '../../../api/user';

const model = ref({
 roleName:'',
 role:'',
 permission:[]
})
const formRef = ref()
const handleCheck = (keys)=>{
  console.log(keys);
  model.value.permission = keys
}
const emit = defineEmits(['update-list'])
const handleRole = async ()=>{
  let _id = ''
  if(props.rowData){
    _id = props.rowData._id
    await roleUpdateApi(_id,model.value) //编辑
  }else{
    let res = await rolePostApi(model.value) //新增
    _id = res.data._id
  }
  emit('update-list',{_id,...model.value})
}

// 接收待编辑数据
const props = defineProps(['rowData'])
if(props.rowData){
  model.value = {...props.rowData}
}
onMounted(()=>{
  console.log('组件初始化渲染');
})
onUnmounted(()=>{
  console.log('组件被销毁了');
})
</script>

<style lang="scss" scoped>
.setting-cont{
 padding-right: 40px;
}
</style>